/*
 * Creative Commons Deed
 * Attribution-NonCommercial-ShareAlike 1.0 Finland
 * 
 * You are free:
 * 
 * * to copy, distribute, display, and perform the work
 * * to make derivative works
 * Under the following conditions:
 * 
 * Attribution. You must attribute the work in the manner specified by the author or licensor.
 * 
 * Noncommercial. You may not use this work for commercial purposes.
 * 
 * Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only 
 * under a license identical to this one.
 * 
 * * For any reuse or distribution, you must make clear to others the license terms of this work.
 * * Any of these conditions can be waived if you get permission from the copyright holder.
 * Your fair use and other rights are in no way affected by the above.
 * This is a human-readable summary of the Legal Code (the full license). 
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using PocketLibrary.Blog;
using PocketLibrary;
using PocketSettings;

namespace PocketApps
{
    public partial class BlogManager : Form
    {

        //TBSettings.Settings Settings = TBSettings.Settings.Create();
        PocketSettings.PocketSettings milkSettings = PocketSettings.PocketSettings.Create();
        //Settings milkSettings = Settings.Create();

        public BlogManager()
        {
            InitializeComponent();
        }

        void Localize()
        {
            try
            {
                this.Text = PocketAppsLocalization.GetString("frmblogs");
                miNewBlog.Text = PocketAppsLocalization.GetString("menunew");
                miCancel.Text = PocketAppsLocalization.GetString("menucancel");
            }
            catch { }
        }


        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void Blogit_Load(object sender, EventArgs e)
        {
            Localize();
            ReadBlogsFromFile();
        }

        private void Blogit_Closing(object sender, CancelEventArgs e)
        {
            if (DialogResult == DialogResult.OK)
                WriteBlogsToFile();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem != null)
                this.DialogResult = DialogResult.OK;
        }


        public void ReadBlogsFromFile()
        {
            try
            {
                XmlDocument blogs = new XmlDocument();
                blogs.Load(milkSettings.Common.Settings.Get("blogsxml"));

                XmlNodeList xmlblogit = blogs.GetElementsByTagName("blog");

                for (int i = 0; i < xmlblogit.Count; i++)
                {

                    if (xmlblogit[i].Attributes["type"].Value.ToString() == "nucleus")
                    {

                        Nucleus bblogi = new Nucleus();

                        bblogi.BlogId = int.Parse(xmlblogit[i].Attributes["id"].Value);
                        bblogi.BlogName = xmlblogit[i].Attributes["name"].Value;
                        bblogi.BlogUrl = xmlblogit[i].Attributes["url"].Value;
                        bblogi.ApiUrl = xmlblogit[i].Attributes["apiurl"].Value;

                        XmlNode auth = xmlblogit[i].SelectSingleNode("descendant::authentication");

                        bblogi.UserName = auth.Attributes["username"].Value;
                        bblogi.PassWord = auth.Attributes["password"].Value;

                        XmlNodeList categories = xmlblogit[i].SelectNodes("descendant::category");

                        bblogi.Categories = new Category[categories.Count];

                        for (int ii = 0; ii < categories.Count; ii++)
                        {
                            Category cat = new Category();
                            cat.CategoryId = categories[ii].Attributes["id"].Value;
                            cat.CategoryName = categories[ii].Attributes["name"].Value;

                            bblogi.Categories[ii] = cat;
                        }
                        listBox1.Items.Add(bblogi);
                    }
                    else if (xmlblogit[i].Attributes["type"].Value.ToString() == "blogger")
                    {

                        Atom bblogi = new Atom();

                        bblogi.BlogId = 0;
                        bblogi.BlogName = xmlblogit[i].Attributes["name"].Value;
                        bblogi.BlogUrl = xmlblogit[i].Attributes["url"].Value;
                        bblogi.ApiUrl = xmlblogit[i].Attributes["apiurl"].Value;

                        XmlNode auth = xmlblogit[i].SelectSingleNode("descendant::authentication");

                        bblogi.UserName = auth.Attributes["username"].Value;
                        bblogi.PassWord = auth.Attributes["password"].Value;

                        XmlNode servicepost = xmlblogit[i].SelectSingleNode("descendant::servicepost");
                        bblogi.ServicePost = servicepost.Attributes["value"].Value;

                        XmlNode servicefeed = xmlblogit[i].SelectSingleNode("descendant::servicefeed");
                        bblogi.ServiceFeed = servicefeed.Attributes["value"].Value;
                        listBox1.Items.Add(bblogi);
                    }
                    else if (xmlblogit[i].Attributes["type"].Value.ToString() == "dokuwiki")
                    {
                        DokuWiki bblogi = new DokuWiki();

                        bblogi.BlogId = 0;
                        bblogi.BlogName = xmlblogit[i].Attributes["name"].Value;
                        bblogi.BlogUrl = xmlblogit[i].Attributes["url"].Value;
                        bblogi.ApiUrl = xmlblogit[i].Attributes["apiurl"].Value;

                        XmlNode auth = xmlblogit[i].SelectSingleNode("descendant::authentication");

                        bblogi.UserName = auth.Attributes["username"].Value;
                        bblogi.PassWord = auth.Attributes["password"].Value;
                        listBox1.Items.Add(bblogi);
                    }

                }
            }
            catch { }
        }

        public void WriteBlogsToFile()
        {
            #region MyRegion
            /*
            using (StreamWriter sw = new StreamWriter(tiedosto))
            {
                for (int i = 0; i < listBox1.Items.Count; i++)
                {
                    NucleusBlogClass item = (NucleusBlogClass)listBox1.Items[i];
                    sw.WriteLine(string.Format("{0}|{1}|{2}|{3}|{4}|{5}^",
                        item.BlogId,
                        item.UserName,
                        item.PassWord,
                        item.BlogUrl,
                        item.BlogName,
                        item.BaseUrl));
                }
            }*/
            #endregion


            using (XmlWriter xw = XmlWriter.Create(milkSettings.Common.Settings.Get("blogsxml")))
            {
                xw.WriteStartDocument();
                xw.WriteStartElement("blogs");

                for (int i = 0; i < listBox1.Items.Count; i++)
                {
                    if (listBox1.Items[i].GetType() == typeof(Nucleus))
                    {
                        Nucleus item = (Nucleus)listBox1.Items[i];
                        xw.WriteRaw(string.Format("<blog id=\"{0}\" name=\"{1}\" url=\"{2}\" apiurl=\"{3}\" type=\"nucleus\">",
                            item.BlogId, item.BlogName, item.BlogUrl, item.ApiUrl));

                        xw.WriteRaw(string.Format("<authentication username=\"{0}\" password=\"{1}\" />", item.UserName, item.PassWord));

                        xw.WriteRaw("<categories>");

                        //item.getBlogCategories();

                        for (int categoryloop = 0; categoryloop < item.Categories.Length; categoryloop++)
                        {
                            xw.WriteRaw(string.Format("<category id=\"{0}\" name=\"{1}\" />",
                                item.Categories[categoryloop].CategoryId,
                                item.Categories[categoryloop].CategoryName));
                        }

                        xw.WriteRaw("</categories>");
                        xw.WriteRaw("</blog>");
                    }
                    else if (listBox1.Items[i].GetType() == typeof(Atom))
                    {
                        Atom item = (Atom)listBox1.Items[i];
                        xw.WriteRaw(string.Format("<blog id=\"{0}\" name=\"{1}\" url=\"{2}\" apiurl=\"{3}\" type=\"blogger\">",
                            0, item.BlogName, item.BlogUrl, item.ApiUrl));
                        xw.WriteRaw(string.Format("<authentication username=\"{0}\" password=\"{1}\" />", item.UserName, item.PassWord));
                        xw.WriteRaw(string.Format("<servicepost value=\"{0}\" />", item.ServicePost));
                        xw.WriteRaw(string.Format("<servicefeed value=\"{0}\" />", item.ServiceFeed));
                        xw.WriteRaw("</blog>");
                    }
                    else if (listBox1.Items[i].GetType() == typeof(DokuWiki))
                    {
                        DokuWiki item = (DokuWiki)listBox1.Items[i];
                        xw.WriteRaw(
                            string.Format("<blog id=\"{0}\" name=\"{1}\" url=\"{2}\" apiurl=\"{3}\" type=\"dokuwiki\">",
                            0, item.BlogName, item.BlogUrl, item.ApiUrl)
                            );

                        xw.WriteRaw(string.Format("<authentication username=\"{0}\" password=\"{1}\" />", item.UserName, item.PassWord));
                        xw.WriteRaw("</blog>");
                    }
                }
                xw.WriteEndDocument();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
        }

        private void menuItem1_Click_1(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }

        private void Blogit_Resize(object sender, EventArgs e)
        {

        }

        private void miCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void miNewBlog_Click(object sender, EventArgs e)
        {
            using (BlogDetails fUusiBlogi = new BlogDetails())
            {
                fUusiBlogi.Owner = this;
                if (fUusiBlogi.ShowDialog() == DialogResult.OK)
                {
                    listBox1.Items.Add(fUusiBlogi.selectedBlog);
                    WriteBlogsToFile();
                }
            }
        }

        private void miDeleteSelectedBlog_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem != null)
                listBox1.Items.Remove(listBox1.SelectedItem);

        }
    }
}